<?php
namespace App\GraphQL\Mutations\Group;

use App\Models\Group;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class UpdateDividendSetting
{

    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $group = $this->validate($args);
        $group->dividend_cate = $args['cate'];
        $group->dividend_scale = $args['scale']*100;
        $group->save();
        return [
            'status' => '200',
            'message' => '更新成功'
        ];
    }

    public function validate($data)
    {
        $cates = [
            'DEFAULT',
            'CUSTOM'
        ];
        $rules = [
            'cate' => [
                'required',
                Rule::in($cates)
            ],
            'scale' => [
                'required',
                'numeric',
                'min: 0',
                'max:100'
            ]
        ];
        if ($data['cate'] == 'STAFF') {
            $rules['device_group_id'] = [
                'required',
                'integer'
            ];
        }
        $messages = [
            'cate.required' => '分类不能为空',
            'cate.in' => '类型不能超出限制',
            'scale.required' => '分成不能为空',
            'scale.numeric' => '分成为数值',
            'scale.min' => '分成为不能小于0%',
            'scale.max' => '分成为不能大于100%',
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
       
        $old = Group::find($data['id']);
        if (! $old) {
            throw new \Exception('群组不存在!');
        }
        return $old;
    }
}
